<template>
  <section
    class="process-design beauty-scroller-bar"
    @click="showAddIndex = -1"
  >
    <section class="left">
      <div class="left-container">
        <div class="left-default-wrap">
          <div
            :class="
              currentVillageId == -1 ? 'left-default-active' : 'left-default'
            "
            @click="onDefaultClick"
          >
            <appstore-outlined style="margin-right: 10px" />默认流程
          </div>
        </div>
        <div class="left-tree-wrap beauty-scroller-bar">
          <a-tree
            v-if="treeList.length"
            show-icon
            :selectedKeys="selectedKeys"
            :tree-data="treeList"
            :blockNode="true"
            :selectable="true"
            :defaultExpandAll="true"
            @select="onTreeSelect"
          >
            <!-- 图标 -->
            <template #icon="{ dataRef }">
              <template v-if="dataRef.isLeaf">
                <bl-icon type="tree-xiangmu" class="tree-icon" />
              </template>
              <template v-else>
                <bl-icon type="tree-jigou" class="tree-icon" />
              </template>
            </template>
          </a-tree>
        </div>
      </div>
    </section>
    <section class="process">
      <template v-for="(process, index) of processList" :key="process.key">
        <div class="box" :class="'bg-' + process.type">
          <div class="title flex-between">
            <span>{{ process.data.name }}</span>
            <a-button
              type="text"
              size="small"
              v-if="!['start', 'end'].includes(process.type)"
              @click="removeProcess(index)"
            >
              <template #icon>
                <CloseOutlined style="color: #fff" />
              </template>
            </a-button>
          </div>
          <div class="content" @click="setProcess(index)">
            <div
              v-if="process.dealerTxt && process.dealerTxt.length"
              class="flex-between text-black"
            >
              <div>
                <div
                  v-for="(text, textIndex) of process.dealerTxt"
                  :key="textIndex"
                >
                  {{ text }}
                </div>
              </div>
              <RightOutlined />
            </div>
            <div class="flex-between text-gray" v-else>
              <span>
                {{
                  process.type == "start" || process.type == "end"
                    ? "添加"
                    : `请设置${process.typeTxt}人`
                }}
              </span>
              <RightOutlined />
            </div>
          </div>
          <div class="alert" v-show="!formDesignList.length || process.error">
            <a-tooltip placement="right" arrow-point-at-center>
              <template #title>
                {{
                  !formDesignList.length
                    ? "表单设计至少需要选择一个控件"
                    : process.error
                }}
              </template>
              <a-button type="link" danger>
                <template #icon>
                  <ExclamationCircleFilled style="font-size: 20px" />
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </div>
        <div class="line" v-if="index != processList.length - 1">
          <a-popover
            :visible="showAddIndex == index"
            placement="right"
            trigger="click"
          >
            <template #content>
              <div class="add-type">
                <div
                  class="add-item"
                  v-for="item of common.addTypeList"
                  :key="item.type"
                  @click.stop="addProcess(item.type, index)"
                >
                  <div class="icon" :class="'bg-' + item.type">
                    <AuditOutlined v-if="item.type == 'approval'" />
                    <SisternodeOutlined v-if="item.type == 'copy'" />
                    <CarryOutOutlined v-if="item.type == 'deal'" />
                  </div>
                  <div class="name">
                    {{ item.title }}
                  </div>
                </div>
              </div>
            </template>
            <div class="add" @click.stop="showAddIndex = index">
              <PlusOutlined />
            </div>
          </a-popover>
        </div>
      </template>
    </section>
    <ProcessSetting
      :visible="processSettingVisible"
      :fromOther="isFromOther"
      :content="processList[currentProcessIndex]"
      @finish="processSettingSuccess"
      @cancel="processSettingCancel"
    />
  </section>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  toRaw,
  toRefs,
  watch,
  createVNode,
} from "vue";
import {
  PlusOutlined,
  RightOutlined,
  AuditOutlined,
  SisternodeOutlined,
  CarryOutOutlined,
  CloseOutlined,
  ExclamationCircleFilled,
  AppstoreOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import common from "../js/common";
import ProcessSetting from "./ProcessSetting.vue";
import store from "../../../../store";
import { useRoute } from "vue-router";
import request from "../../../../common/utils/request";
import { BlIcon } from "bl-common-vue3";
import { message, Modal } from "ant-design-vue";
import utils from "@/common/utils/utils";

export default defineComponent({
  name: "ProcessDesign",
  components: {
    ProcessSetting,
    PlusOutlined,
    RightOutlined,
    AuditOutlined,
    SisternodeOutlined,
    CarryOutOutlined,
    CloseOutlined,
    ExclamationCircleFilled,
    "bl-icon": BlIcon,
    AppstoreOutlined,
  },
  props: {
    trigger: {
      type: Number,
      default: 0,
    },
    approvalId: {
      type: [Number, String],
      default: 0,
    },
    isFromOther: {
      type: Boolean,
      default: false,
    },
    alias:{
      type:String,
      default:'',
    },
    id:{
      type:[Number,String],
      default:0,
    }
  },
  setup(props, { emit }) {
    const route = useRoute();

    const state = reactive({
      id: route.query.id,
      processList: [],
      showAddIndex: -1,
      processSettingVisible: false,
      currentProcessIndex: {},

      treeList: [],
      selectedKeys: [],
      processChanged: false,
      currentVillageId: -1,
    });

    const formDesignList = computed(() => store.getters.approvalFormDesign);

    // 设置流程
    const setProcess = (index) => {
      state.currentProcessIndex = index;
      state.processSettingVisible = true;
    };
    // 设置流程成功
    const processSettingSuccess = (processInfo) => {
      state.processList[state.currentProcessIndex] = JSON.parse(
        JSON.stringify(processInfo)
      );
      console.log("-----------------processSettingSuccess", toRaw(processInfo));
      state.processSettingVisible = false;
      state.processChanged = true;
    };
    // 取消设置流程
    const processSettingCancel = () => {
      state.currentProcessIndex = -1;
      state.processSettingVisible = false;
    };

    // 添加流程
    let processCount = 0;
    const addProcess = (type, index) => {
      let item = {};
      processCount++;
      switch (type) {
        case "approval":
          Object.assign(item, common.defaultApproval);
          break;
        case "copy":
          Object.assign(item, common.defaultCopy);
          break;
        case "deal":
          Object.assign(item, common.defaultDealer);
          break;
      }
      item.key = type + "_" + processCount;
      state.processList.splice(index + 1, 0, item);
      state.showAddIndex = -1;
      state.processChanged = true;
      validateForm()
    };

    // 删除流程
    const removeProcess = (index) => {
      state.processList.splice(index, 1);
      state.processChanged = true;
      validateForm()
    };

    const validateForm = () => {
      store.dispatch("SetProcessDesign", state.processList).then(() => {
        emit("triggerChange", state.processList, state.currentVillageId);
      });
    };

    watch(
      () => props.trigger,
      () => {
        validateForm();
      }
    );

    watch(
      () => store.getters.approvalCurrentStep,
      (step) => {
        if (step > 0) {
          nextTick(() => {
            state.processList.forEach((process) => {
              const { data, type } = process;
              if (
                (type == "approval" || type == "deal") &&
                data.approverEmpty == 3 &&
                !data.emptyAdmin &&
                !process.error
              ) {
                const adminUserList =
                  store.getters.approvalBasicInfo.adminUserList;
                if (adminUserList && adminUserList.length) {
                  data.emptyAdmin = adminUserList[0].value;
                } else {
                  process.error = "未选择审批管理员";
                }
              }
            });
          });
        }
      }
    );

    const approvalDetail = computed(() => store.getters.approvalDetail);

    const getVillageList = () => {
      request
        .get("/org", "/build/villageAndBuildList/v2", {
          checked: 1,
          attach_department: 1,
        })
        .then((res) => {
          console.log(res);
          let result = [];
          if (res.list && res.list.length > 0) {
            let orgInfo = res.list[0];
            let obj = {
              title: orgInfo.name,
              key: orgInfo.id,
              children: [],
            };
            if (orgInfo.villageList && orgInfo.villageList.length > 0) {
              orgInfo.villageList.forEach((item) => {
                obj.children.push({
                  title: item.name,
                  // key: "org_" + orgInfo.id + "_village_" + item.id,
                  key: "org_" + item.org_id + "_village_" + item.id,
                  villageId: item.id,
                  villageInfo: item,
                  isLeaf: true,
                });
              });
            }
            result.push(obj);
          }
          state.treeList = result;
          console.log("state.treeList", state.treeList);
        });
    };

    const getVillageProcess = (villageId) => {
      request
        .get("/work_approval", "/manage/approval/process", {
          id: props.approvalId,
          village_id: villageId,
        })
        .then((res) => {
          if (
            res.process &&
            Array.isArray(res.process) &&
            res.process.length > 0
          ) {
            state.processList = res.process;
          } else {
            state.processList = JSON.parse(
              JSON.stringify(common.defaultProcess)
            );
          }
        });
    };

    const onTreeSelect = (value, e) => {
      if (e.node.isLeaf) {
        let id;
        id = e.node.dataRef.villageId;
        if (state.processChanged && id != state.currentVillageId) {
          Modal.confirm({
            title: () => "提示",
            icon: () => createVNode(ExclamationCircleOutlined),
            content: () => "当前修改操作未保存，是否继续？",
            onOk() {
              state.processChanged = false;
              state.selectedKeys = value;
              state.currentVillageId = id;
              if (props.approvalId) {
                // 编辑时查询项目下的审批流程
                getVillageProcess(id);
              } else {
                // 新建时重置为默认流程
                state.processList = JSON.parse(
                  JSON.stringify(common.defaultProcess)
                );
              }
            },
          });
        } else {
          state.processChanged = false;
          state.selectedKeys = value;
          state.currentVillageId = id;
          if (props.approvalId) {
            // 编辑时查询项目下的审批流程
            getVillageProcess(id);
          } else {
            // 新建时重置为默认流程
            state.processList = JSON.parse(
              JSON.stringify(common.defaultProcess)
            );
          }
        }
        store.dispatch("SetProcessDesign", state.processList).then(() => {
          emit("triggerChange", state.processList, state.currentVillageId);
        });
      } else {
        return;
      }
    };

    const onDefaultClick = () => {
      state.processChanged = false;
      state.selectedKeys = [];
      state.currentVillageId = -1;

      if (props.id) {
        state.processList = approvalDetail.value.process.length?approvalDetail.value.process:JSON.parse(JSON.stringify(common.defaultProcess));
      } else {
        // 重置为默认流程
        state.processList = JSON.parse(JSON.stringify(common.defaultProcess));
      }
      store.dispatch("SetProcessDesign", state.processList).then(() => {
        emit("triggerChange", state.processList, 0);
      });
    };

    const init = () => {
      if (props.id|| props.alias) {
        watch(
          () => approvalDetail.value,
          (detail) => {
            if (detail && detail.id) {
              if (detail.process.length) {
                state.processList = detail.process;
              } else {
                state.processList = JSON.parse(
                  JSON.stringify(common.defaultProcess)
                );
              }
              processCount = state.processList.length;
            }
          }
        );
      } else {
        state.processList = JSON.parse(JSON.stringify(common.defaultProcess));
      }
      getVillageList();
    };

    init();

    return {
      common,
      formDesignList,
      approvalDetail,
      ...toRefs(state),
      addProcess,
      removeProcess,
      setProcess,
      processSettingSuccess,
      processSettingCancel,

      onTreeSelect,
      onDefaultClick,
    };
  },
});
</script>
<style lang="less" scoped>
@startColor: #a9b4cd;
@approvalColor: #ff8800;
@dealColor: #935af6;
@copyColor: #3370ff;

.process-design {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  .process {
    margin: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    .box {
      width: 250px;
      border-radius: 8px;
      padding: 8px;
      position: relative;
      .title {
        color: #fff;
      }
      .content {
        margin-top: 4px;
        background: #fff;
        padding: 4px 8px;
        border-radius: 4px;
        color: rgba(0, 0, 0, 1);
        cursor: pointer;
      }
      .alert {
        position: absolute;
        right: -40px;
        top: 0px;
      }
    }
    .line {
      width: 1px;
      height: 100px;
      background: #ccc;
      position: relative;
      .add {
        position: absolute;
        width: 30px;
        height: 30px;
        top: calc(50% - 15px);
        left: -15px;
        // transform: translate(-50%, -50%);
        border-radius: 50%;
        background: #fff;
        box-shadow: @box-shadow-base;
        display: flex;
        align-items: center;
        justify-content: center;
        color: @primary-color;
        font-size: 18px;
        cursor: pointer;
        border: 1px solid transparent;
        &:hover {
          transform: scale(1.2);
          border: 1px solid @primary-color;
        }
      }
    }
  }

  .left {
    width: 300px;
    padding: 20px;

    .left-container {
      background-color: #fff;
      border: 1px solid #ddd;
      width: 100%;
      height: 100%;
      border-radius: 10px;
      padding: 20px;

      .left-default-wrap {
        border-bottom: 1px dotted #ddd;
        height: 45px;

        .left-default {
          cursor: pointer;
          padding: 5px 20px;
          border-radius: 2px;
        }

        .left-default-active {
          cursor: pointer;
          padding: 5px 20px;
          border-radius: 2px;
          background-color: #bae7ff;
        }
      }

      .left-tree-wrap {
        width: 100%;
        height: calc(100% - 45px);
        overflow: hidden auto;
        padding: 20px 5px 20px 0;
      }
    }

    :deep(.ant-tree) {
      background-color: transparent;
    }

    :deep(.ant-tree .ant-tree-node-content-wrapper:hover) {
      background-color: #f1f1f1;
    }
  }
}
.add-type {
  display: flex;
  align-items: center;
  .add-item {
    padding: 10px 20px;
    text-align: center;
    cursor: pointer;
    border-radius: 4px;
    &:hover {
      background: #f4f4f4;
    }
    .icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 24px;
    }
    .name {
      font-size: 14px;
      margin-top: 4px;
      color: #000;
    }
  }
}
.bg-start,
.bg-end {
  background: @startColor;
}
.bg-approval {
  background: @approvalColor;
}
.bg-deal {
  background: @dealColor;
}
.bg-copy {
  background: @copyColor;
}
.color-start,
.color-end {
  color: @startColor;
}
.color-approval {
  color: @approvalColor;
}
.color-deal {
  color: @dealColor;
}
.color-copy {
  color: @copyColor;
}
</style>
